<template>
  <div class="form-data-source-config">
    <!-- 表单数据源配置 -->
    <a-card title="表单数据源配置" size="small">
      <div style="margin-bottom: 16px;">
        <a-button type="primary" @click="showFormModal = true">
          选择数据源
        </a-button>
        <a-button style="margin-left: 8px;" @click="showExtractModal(formFields, '表单字段')">
          快速提取
        </a-button>
        <a-button style="margin-left: 8px;" @click="clearAllFields" type="default">
          清空数据源
        </a-button>
      </div>
      
      <a-table 
        :columns="fieldColumns" 
        :data-source="formFields" 
        :pagination="false"
        :scroll="{ y: 300 }"
        :row-key="(record) => record.fieldKey"
        class="fixed-height-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'fieldName'">
            <a-tooltip :title="record.fieldName">
              <span class="ellipsis-cell">{{ record.fieldName }}</span>
            </a-tooltip>
          </template>
          <template v-else-if="column.key === 'description'">
            <div v-if="editingKey !== record.fieldKey" @click="editDescription(record)" class="editable-cell">
              <a-tooltip :title="record.description">
                <span class="ellipsis-cell">{{ record.description }}</span>
              </a-tooltip>
            </div>
            <a-input 
              v-else
              ref="editInputRef"
              v-model:value="record.description"
              @blur="saveDescription(record)"
              @keydown.enter="saveDescription(record)"
              size="small"
            />
          </template>
          <template v-else-if="column.key === 'componentType'">
            <a-select 
              v-model:value="record.componentType" 
              :options="componentTypeOptions"
              size="small"
              style="width: 120px;"
              @change="updateModelValue"
            />
          </template>
          <template v-else-if="column.key === 'operation'">
            <a-button type="link" @click="removeFormField(record)">删除</a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 数据源选择弹窗 -->
    <DataSourceSelectionModal 
      v-model:open="showFormModal"
      @confirm="handleFormSourceConfirm"
    />
    
    <!-- 数据提取弹窗 -->
    <a-modal
      v-model:open="extractModalVisible"
      :title="extractModalTitle"
      width="600px"
      :footer="null"
    >
      <div style="margin-bottom: 16px;">
        <a-button type="primary" @click="copyToClipboard">
          复制到剪贴板
        </a-button>
      </div>
      <pre style="background-color: #f5f5f5; padding: 12px; border-radius: 4px; max-height: 400px; overflow: auto;">
{{ extractDataJson }}
      </pre>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import DataSourceSelectionModal from '../DataSourceSelectionModal.vue'
import { message } from 'ant-design-vue'
import LogManager from '../../logUtils.js'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ formFields: [] })
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue'])

// 组件类型选项
const componentTypeOptions = [
  { label: 'Input', value: 'Input' },
  { label: 'Select', value: 'Select' },
  { label: 'DatePicker', value: 'DatePicker' },
]

// 表格列定义
const fieldColumns = [
  {
    title: '参数名',
    dataIndex: 'fieldName',
    key: 'fieldName'
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '数据类型',
    dataIndex: 'componentType',
    key: 'componentType'
  },
  {
    title: '操作',
    key: 'operation'
  }
]

// 表单字段
const formFields = ref(props.modelValue.formFields || [])

// 控制弹窗显示
const showFormModal = ref(false)

// 提取数据弹窗相关
const extractModalVisible = ref(false)
const extractModalTitle = ref('')
const extractDataJson = ref('')

// 编辑状态相关
const editingKey = ref('')
const editInputRef = ref()

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    formFields.value = newVal.formFields || []
  }
}, { deep: true })

// 处理表单数据源确认事件
const handleFormSourceConfirm = (data) => {
  addFields(formFields, data)
}

// 添加字段到指定数组
const addFields = (targetArray, data) => {
  let fieldId = Date.now() // 使用时间戳作为基础ID
  data.selectedFields.forEach(field => {
    const fieldRecord = {
      fieldKey: `${fieldId++}`,
      fieldName: field.label,
      description: field.description,
      sourcePath: data.path,
      sourceMethod: data.method,
      componentType: 'Input' // 默认为Input类型
    }
    targetArray.value.push(fieldRecord)
  })
  
  // 更新modelValue
  updateModelValue()
}

// 删除表单字段
const removeFormField = (record) => {
  const index = formFields.value.findIndex(item => item.fieldKey === record.fieldKey)
  if (index > -1) {
    formFields.value.splice(index, 1)
    updateModelValue()
  }
}

// 更新modelValue
const updateModelValue = () => {
  emit('update:modelValue', {
    formFields: formFields.value
  })
}

// 显示提取数据弹窗
const showExtractModal = async (data, title) => {
  extractModalTitle.value = `${title}数据提取`
  
  // 表单字段使用查询字段格式: [{"label":"测试字段","field":"test1"}]
  const formattedData = data.map(item => ({
    label: item.description,
    field: item.fieldName
  }))
  extractDataJson.value = JSON.stringify(formattedData, null, 2)
  
  // 记录日志
  await LogManager.logAction('提取表单字段数据', 1, {
    fields: formattedData.map(item => item.field),
    fieldsCount: formattedData.length
  })
  
  extractModalVisible.value = true
}

// 复制到剪贴板
const copyToClipboard = () => {
  // 检查浏览器是否支持Clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(extractDataJson.value)
      .then(() => {
        message.success('已复制到剪贴板')
      })
      .catch(err => {
        console.error('复制失败:', err)
        message.error('复制失败，请手动复制')
      })
  } else {
    // 降级处理：使用传统的execCommand('copy')方法
    try {
      const textArea = document.createElement('textarea')
      textArea.value = extractDataJson.value
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      const successful = document.execCommand('copy')
      document.body.removeChild(textArea)
      
      if (successful) {
        message.success('已复制到剪贴板')
      } else {
        message.error('复制失败，请手动复制')
      }
    } catch (err) {
      console.error('复制失败:', err)
      message.error('复制失败，请手动复制')
    }
  }
}

// 编辑描述
const editDescription = (record) => {
  editingKey.value = record.fieldKey
  // 保存原始值，用于取消时恢复
  record.originalDescription = record.description
  nextTick(() => {
    if (editInputRef.value) {
      editInputRef.value.focus()
    }
  })
}

// 保存描述
const saveDescription = (record) => {
  // 如果输入为空，则恢复为原始值
  if (!record.description || record.description.trim() === '') {
    record.description = record.originalDescription
  }
  editingKey.value = ''
  updateModelValue()
}

// 清空所有字段
const clearAllFields = () => {
  formFields.value = []
  updateModelValue()
}
</script>

<style scoped>
.form-data-source-config {
  padding: 10px 0;
}

.editable-cell {
  cursor: pointer;
  padding: 4px 11px;
  margin: -4px -11px;
  border-radius: 2px;
  transition: all 0.3s;
}

.editable-cell:hover {
  background-color: #f5f5f5;
}

/* .fixed-height-table {
  height: 450px;
} */

/* 添加省略显示样式 */
.ellipsis-cell {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加紧凑型表格样式 */
:deep(.ant-table-tbody > tr > td) {
  padding: 4px 8px;
}

:deep(.ant-table-thead > tr > th) {
  padding: 8px;
}

:deep(.ant-table) {
  font-size: 12px;
}

:deep(.ant-select) {
  font-size: 12px;
}

/* 缩小操作列按钮 */
:deep(.ant-btn-link) {
  padding: 0 4px;
  font-size: 12px;
  height: auto;
  line-height: 1.5;
}
</style>